<?php
/**
 * @fileoverview    封装发布模块
 * @author          gaojian3
 * @date            2012-04-09
 * @copyright       sina meila
 * @param           
 * @param             
 * @return             
 */

include(SERVER_ROOT_PATH.'/include/config/dataRule/ml_datarule_content.php');
include(SERVER_ROOT_PATH.'/include/config/ml_queue_name.php');

class ml_biz_publish{

    public $result;

    public function __construct($data){
        $this->content = $data['content'];
        $this->wb_pid=$data['wb_pid'];         //微活动上图片资源的id，类似rid
        $this->wb_pic_id=$data['wb_pic_id'];     //微博上图片唯一标识
        $this->wb_pic_url=$data['wb_pic_url'];     //微博上图片地址
        $this->pic_id =  $data['pic_id'];      //上传图片后得到的pic_id
        $this->gd_title = $data['gd_title'];
        $this->gd_price = $data['gd_price'];
        $this->gd_url = $data['gd_url'];
        $this->gd_pic = $data['gd_pic'];       //商品图片
        $this->pb2weibo = $data['pb2weibo'] ;
        $this->col_id = intval($data['col_id'] );
        $this->ctype = (int)$this->data['ctype'];
        $this->from=$data['from'];
        $this->uid=$data['uid'];
    }

    public function checkParam(){
        if(!$rs=$this->checkContent())
            return $this->result;
            
        if(!empty($this->gd_title) && !empty($this->gd_url)){    
            if(empty($this->pic_id)){
                $this->type_xrank = ML_CONTENT_XRANK_GOODS;
                $this->fetchImg($this->gd_pic);
            }else{
                $this->type_xrank = ML_CONTENT_XRANK_IMGOODS;
            }
        }else{
            if(!empty($this->wb_pic_id)){
                $this->fetchImg($this->wb_pic_url);  //手机版发搭配参与活动返回图片url
            }
            if(!empty($this->pic_id)){
                if(!$this->checkPicid()){
                    return $this->result;
                }
            }
        }
        switch($this->type_xrank){
            case ML_CONTENT_XRANK_GOODS:              //只发商品
            case ML_CONTENT_XRANK_IMGOODSGOODS:     //同时发商品和搭配
                if(!$rs=$this->checkTitle())
                    return $this->result;
                if(!$rs=$this->checkPrice())
                    return $this->result;
                if(!$rs=$this->checkGdurl())
                    return $this->result;
                if(!$rs=$this->checkGdpic())
                    return $this->result;
                break;
            case ML_CONTENT_XRANK_IMG:              //只发搭配
                break;
        }
        $this->result['code']=ML_RCODE_SUCC;
        return $this->result;
    }
    public function findNick(){
        $aNicks = ml_tool_nick::findAllAtNick($this->content);
        if($aNicks){
            return ml_tool_nick::nicks2uids($aNicks);
        }
    }
    public function main(){
        $oGenerator = new ml_model_dbIdGenerator();
        $this->modelBox=new ml_model_dbCollectionBox();
        $aN2u = $this->findNick();
    
        $this->userfeed_data['ctime'] = $this->content_data['ctime'] = date('Y-m-d H:i:s', time());
        $this->userfeed_data['uid'] = $this->content_data['uid'] = $this->uid;
        $this->userfeed_data['content'] = $this->content_data['content'] = $this->content;
        $this->userfeed_data['cip'] = $this->content_data['cip'] = Tool_ip::get_real_ip();
        $this->userfeed_data['from'] = $this->content_data['from'] = $this->from;
        
        if(!empty($this->pic_id)){
            $content_res = $oGenerator->get_content_rid($this->uid, $this->content_rid);
            $userfeed_res = $oGenerator->get_userfeed_rid($this->uid, $this->userfeed_rid);
            if(! $content_res && $userfeed_res){
                $this->result['code']=ML_RCODE_BUSY;
                $this->result['msg']=ML_RMESSAGE_BUSY;
                return $this->result;
            }
            $this->content_data['type_xrank'] = $this->type_xrank;
            $this->userfeed_data['content_rid'] = $this->content_data['rid'] = $this->content_rid;
            $this->userfeed_data['pic_id'] = $this->content_data['pic_id'] = $this->pic_id;
            $this->userfeed_data['rid'] = $this->content_data['userfeed_rid'] = $this->userfeed_rid;
            $this->userfeed_data['type'] = Tool_dataMultiplex::isAttribute(ML_CONTENT_XRANK_GOODS,$this->type_xrank) ? ML_FEED_TYPE_PUB_DOTEY : ML_FEED_TYPE_PUB_PIC;
            
            if(!empty($this->gd_title)){
                $this->content_data['gd_title'] = $this->gd_title;
                $this->content_data['gd_price'] = $this->gd_price;
                $this->content_data['gd_info'] = array(
                    'gd_url'=>$this->gd_url,
                    'gd_pic'=>$this->gd_pic,
                );
                $this->userfeed_data['feed_info'] = array(
                    'gd_title'=>$this->gd_title,
                    'gd_price'=>$this->gd_price,
                    'gd_url'=>$this->gd_url,
                    'gd_pic'=>$this->gd_pic,
                );
            }
            //将用户输入的昵称保存备查 shaopu@
            if(!empty($aN2u)){
                $this->content_data['gd_info']['nick2uid']= $aN2u;
                $this->userfeed_data['feed_info']['nick2uid']= $aN2u;
            }
            
            $oContent = new ml_model_dbContent();
            $rDb_content = $oContent->insert_content($this->content_data);
            if($rDb_content){
                if(!empty($this->gd_title))
                    $rMq_analyse = ml_tool_sendMq::goods_title_analyse($this->content_rid, $this->gd_title);
                $rMq_content = ml_tool_sendMq::goods_add_content($this->content_data);    
                ml_tool_sendMq::search_content('A',$this->content_rid);
                if(!empty($this->col_id)&&$this->col_id>0){            //收集到专辑
                    $rs=$this->addCol();
                    if($rs['code']==ML_RCODE_BUSY){
                        return $rs;
                    }
                }
            }
        }else{
            $userfeed_res = $oGenerator->get_userfeed_rid($this->uid, $this->userfeed_rid);
            if(!$userfeed_res){
                $this->result['code']=ML_RCODE_BUSY;
                $this->result['msg']=ML_RMESSAGE_BUSY;
                return $this->result;
            }
            $this->userfeed_data['rid'] = $this->userfeed_rid;
            $this->userfeed_data['type'] = ML_FEED_TYPE_PUB_SHORT;
            //将用户输入的昵称保存备查 shaopu@
            if(!empty($aN2u)){
                $this->userfeed_data['feed_info']['nick2uid'] = $aN2u;
            }
        }
                
        $rid = $this->content_rid ? $this->content_rid : $this->userfeed_rid;
        if(!empty($aN2u))
            ml_tool_sendMq::atme_in_content($this->uid , $rid , array_values($aN2u));

        $oUserfeed = new ml_model_dbUserfeed();
        $rDb_userfeed = $oUserfeed->insert_content($this->userfeed_data);
        
        $this->oRedis = new ml_model_rdsCount();
        $this->oRedis->incrUserContentcnt($this->uid);  //增加统计数
        $this->oRedis->incrUserfeedcnt($this->uid);
        /**
         * @todo 发布到微博待处理
         */
        
        if($this->pb2weibo){
            $this->send_weibo();    
        }
        
        if(!$rDb_userfeed){
            $this->result['code']=ML_RCODE_BUSY;
            $this->result['msg']=ML_RMESSAGE_BUSY;
        }else{
            $at_num = count($aN2u);
            //行为日志
            switch($this->from){
                case ML_FROM_WEB:
                    $from='0';
                    break;
                case ML_FROM_PHONE:
                    $from= MLAPP_FROM_VDAPEI;
                    break;
            }
            switch($this->type_xrank){
                case ML_CONTENT_XRANK_GOODS:
                    ml_tool_actionlog::publish_gd($uid, $this->gd_url, $this->content , false , $at_num,$from);
                    break;
                case ML_CONTENT_XRANK_IMG:
                    ml_tool_actionlog::publish_pic($uid, $this->content , $at_num,$from);
                    break;
                case ML_CONTENT_XRANK_IMGOODS:
                    ml_tool_actionlog::publish_gd($uid, $this->gd_url, $this->content,true , $at_num,$from);
                    break;
                default:
                    ml_tool_actionlog::publish_txt($uid, $this->content , $at_num ,$from);
            }

            $this->result['code']=ML_RCODE_SUCC;
            $this->result['content_data']=$this->content_data;
        }
        return $this->result;
    }
    
    public function parse_title(){
        
        $wbcontent=urldecode($this->content);
        $wbgd_title=urldecode($this->gd_title);
        if($wbcontent=='分享宝贝'){
            $wbcontent='我刚刚在 @美啦 分享了【'.$wbgd_title.'】 >> http://meila.com'. ml_tool_urlMaker::show_goods($this->content_rid);
        }elseif($wbcontent=='分享图片'){
            $wbcontent='我刚刚在 @美啦 发布了我的搭配照片 >> http://meila.com'.ml_tool_urlMaker::show_goods($this->content_rid);
        }else{
            if(empty($this->content_rid)){
                $wbcontent=$wbcontent.' >> http://meila.com'.ml_tool_urlMaker::person_feed($this->uid);
            }else{
                $wbgd_title=empty($wbgd_title)?'':'【'.$wbgd_title.'】';
                $wbcontent=$wbcontent.' '.$wbgd_title.' >> http://meila.com'.ml_tool_urlMaker::show_goods($this->content_rid);
            }
        }
        return $wbcontent;
    }
    
    public function send_weibo(){
        $session=ml_controller::getSession();
        $wb['access_token']=$session->getVal ( 'access_token' );
        $wbcontent=$this->parse_title();
        switch($this->type_xrank){
            case ML_CONTENT_XRANK_GOODS:
                $wb['picurl']=$this->gd_pic;
                break;
            case ML_CONTENT_XRANK_IMG:
            case ML_CONTENT_XRANK_IMGOODS:
                $wb['picurl']=ml_tool_picid::pid2url($this->pic_id,ML_USER_PICSIZE_SHOW,ML_PICTYPE_CONTENT);
                break;
            default:
                break;
        }
        $wb['content']=$wbcontent;
        $service_id = 1;     //weibo
        ml_tool_sendMq::send_3rdweibo($service_id,$wb);
    }
    
    
    //main返回A00006后，可调用pubHtml
    public function pubHtml(){
        $data = array('feed_rid' => $this->userfeed_rid, 'uid' => $this->uid);
        ml_tool_sendMq::add_feed($data);
        if(!empty($this->pic_id) && $this->ctype){
            $outData['ctype'] = $this->ctype;
            $outData['data'] = ml_tool_pinOutput::parsePinboardTpl(array($this->content_data));
            $outData['data'] = str_replace("height:0px","",$outData['data'][0]);
        }else{
            $outData['ctype'] = $this->ctype;
            $htmlModel=new ml_biz_user_feed();
            $auid[] = $this->uid;
            $outData['data'] = $htmlModel->get_html(array($this->userfeed_data), $auid, true);
            $outData['data'] = $outData['data'][0];
        }
        return $outData;
    }
    
    public function addCol(){
        $modelRe=new ml_model_dbCollectionRe();
        $comModel=new ml_model_dbCollectionComment();
        
        if(!$rs=$this->get_col_id()){   //其中的name用来插入评论表，作为冗余name
            return $this->result;
        }
        $this->col_info_factory();
        $modelRe->submitRepost($this->uid,$this->col_id,$this->content_rid,'');//向关系表中加一个记录
        $this->modelBox->submitRepost($this->uid,$this->col_id,$this->col_info);//采集数+1&update专辑的前9个图片
        $comModel->insert_comment($this->content_rid, $this->infoAndName['name'], $this->uid, $this->col_id, '');
        
        $this->redis->incrColCnt($this->content_rid);//宝贝被转采数+1
    }
    
    private function get_col_id(){
        $this->infoAndName=$this->modelBox->getColinfo($this->uid, $this->col_id);
        if (empty($this->infoAndName['name'])) {
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='wrong col_id';
            return false;
        }
        return true;
    }
    private function col_info_factory(){
        $this->col_info=$this->infoAndName['col_info'];
        $this->col_info=empty($this->col_info)?array():$this->col_info;
        if(count($this->col_info)>=9) array_pop($this->col_info);
        $this->col_info=array_merge(array($this->pic_id),$this->col_info);
    }
   
    public function checkPicid(){
        if(!preg_match('/^[a-zA-Z0-9]{19}$/',$this->pic_id)){
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='pic_id';
            return false;
        }
        $this->type_xrank = ML_CONTENT_XRANK_IMG;
        return true;
    }
       public function checkGd(){
          if(!empty($this->gd_price) || !empty($this->gd_url) || !empty($this->gd_pic)){
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='gd_exit';
            return false;
        }
        return true;
    }
    public function checkTitle(){
        if(Tool_string::str_width($this->gd_title)>ML_DATARULE_CONTENT_TITLE_MAXLEN){
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='gd_title_len';
            return false;
        }
        return true;
    }
    public function checkPrice(){
        if(empty($this->gd_price)  || !is_numeric($this->gd_price)){
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='gd_price';
            return false;
        }
        return true;
    }
    public function checkGdurl(){
        if(empty($this->gd_url) || !preg_match(ML_DATARULE_BASE_URL , $this->gd_url)){
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='gd_url';
            return false;
        }
        return true;
    }
    public function checkGdpic(){
        if(empty($this->gd_pic) || !preg_match(ML_DATARULE_BASE_URL , $this->gd_pic)){
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='gd_pic';
            return false;
        }
        return true;
    }
    public function fetchImg($picUrl){
        $fetchImg = 'http://upload.image.meila.com/interface/bg_ml_fetchImg.php';
        $data['imgurl'] = $picUrl;
        $data['uid'] = $this->uid;
        $rs = Tool_http::post($fetchImg,$data);
        $rs = json_decode($rs, true);
        if ($rs['code'] == ML_RCODE_SUCC) {
            $this->pic_id = $rs['data'];
        } else {
            $this->pic_id = 0;
        }
    }
    public function checkContent(){
        if(empty($this->content)){
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='content';
            return false;
        }
        //$this->content=Tool_keyword::filterSensitiveWord($this->content);
        if(Tool_string::str_width($this->content) > ML_DATARULE_CONTENT_MAXLEN){
            $this->result['code']=ML_RCODE_PARAM;
            $this->result['msg']='content_len';
            return false;
        }
        return true;
    }
}